package com.rrs.client.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.rrs.client.R
import com.rrs.client.Utils
import com.rrs.client.databinding.ItemPolicyBinding
import com.rrs.client.detail.PolicyDetailActivity
import com.rrs.client.entity.Policy
import kotlinx.coroutines.DelicateCoroutinesApi
import okhttp3.OkHttpClient
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale


internal class PolicyAdapter(
    private val context: Context,
    private val list: List<Policy>,
) :
    RecyclerView.Adapter<PolicyAdapter.ViewHolder>() {
    val utils = Utils(context)
    val client = OkHttpClient()
    var formatter = SimpleDateFormat("yy/MM/dd HH:mm", Locale.CHINA)

    internal class ViewHolder(binding: ItemPolicyBinding) :
        RecyclerView.ViewHolder(binding.root) {
        var main = binding.main
        var title = binding.title
        var date = binding.date
        var coverImg = binding.coverImg
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PolicyAdapter.ViewHolder {
        val binding = ItemPolicyBinding
            .inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    @OptIn(DelicateCoroutinesApi::class)
    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: PolicyAdapter.ViewHolder, position: Int) {
        val item = list[position]
        holder.title.text = item.title
        holder.date.text = formatter.format(Date(item.postTime!!.time))
        Glide.with(context)
            .load("${context.resources.getString(R.string.ServerUrl)}/getFile?name=${item.coverImg}&path=PolicyCover/")
            .into(holder.coverImg)
        holder.main.setOnClickListener {
            val intent = Intent()
            intent.setClass(context, PolicyDetailActivity::class.java)
            intent.putExtra("id", "${item.id}")
            context.startActivity(intent)
        }
    }

    override fun getItemCount(): Int {
        return list.size
    }

}